#include <ctype.h>
#include <limits.h>
#include <math.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* spiralOrder(int** matrix, int matrixSize, int* matrixColSize, int* returnSize);

int main()
{
	return 0;
}

int* spiralOrder(int** matrix, int matrixSize, int* matrixColSize, int* returnSize)
{
	int rowLen = matrixSize, size = 0; *returnSize = 0;
	if (!rowLen) return NULL; int colLen = *matrixColSize;
	*returnSize = rowLen * colLen; int* res = calloc(*returnSize, sizeof(int));

	int left = 0, right = colLen - 1, top = 0, bottom = rowLen - 1, bound = *returnSize;
	while (true) {
		for (int i = left; i <= right; i++)
			res[size++] = matrix[top][i];
		top++; if (size == bound) break;
		for (int i = top; i <= bottom; i++)
			res[size++] = matrix[i][right];
		right--; if (size == bound) break;
		for (int i = right; i >= left; i--)
			res[size++] = matrix[bottom][i];
		bottom--; if (size == bound) break;
		for (int i = bottom; i >= top; i--)
			res[size++] = matrix[i][left];
		left++; if (size == bound) break;
	}

	return res;
}